<template>
	<view>
		<view class="title-box m-t-26">
			{{form.title}}
		</view>
		<u--form :model="form" ref="uForm">
			<u-form-item label="汇报时间:" prop="name" labelWidth="75">
				<view class="">
					{{reportingTime}}
				</view>
			</u-form-item>
			<u-form-item label="汇报给:" prop="name" labelWidth="75">
				<view class="d-flex hbr-box">
					<view class="hbr-item" v-for="item in leader">
						{{item.nickName}}
					</view>
				</view>
			</u-form-item>

			<u-form-item label="完成状态:" labelWidth="75" @click="showSex = true" required>
				<u--input v-model="yj_status" disabled disabledColor="#ffffff" placeholder="请选择完成状态"
					border="none" style="pointer-events: none;"></u--input>

				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item label="汇报内容" prop="name" labelWidth="160" labelPosition="top" required>
				<view class="m-t-10 width-100 d-flex a-item-c">
					<template v-if="type == 0">
						<u-input v-model="form.name" type="text" placeholder="仅允许输入数字、小数点，且最多保留6位小数"
							@change="handleInput" />
						<text class="m-l-10">{{form.unit}}</text>
					</template>
					<template v-else>
						<u--textarea v-model="form.name" placeholder="请输入内容"></u--textarea>
					</template>
				</view>
			</u-form-item>

			<u-form-item label="任务跟进方式:" labelWidth="105" @click="showtype = true" required>
				<u--input v-model="yj_type" disabled disabledColor="#ffffff" placeholder="请选择任务跟进方式"
					border="none" style="pointer-events: none;"></u--input>

				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item label="凭证" prop="name" labelWidth="160" labelPosition="top" required>
				<view class="m-t-10 width-100">
					<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
						:maxCount="10" width="100" height="100"></u-upload>

				</view>
			</u-form-item>
		</u--form>
		<view class="btn-box">
			<u-button @click="submit" class="btn-submit">提交</u-button>
			<!-- <u-button @click="share" class="btn-submit-2">分享</u-button> -->
		</view>
		<u-picker keyName="label" :show="showSex" :columns="status_columns" @confirm="confirm" @cancel="showSex = false"
			confirmColor="#2585f5"></u-picker>
		<u-picker keyName="label" :show="showtype" :columns="type_columns" @confirm="confirm2"
			@cancel="showtype = false" confirmColor="#2585f5"></u-picker>
	</view>
</template>

<script>
	import {
		http,API_BASE_URL
	} from '@/common/http.js';
	import {
		addPerformance,
		selectPerformanceDetail,
		selectPerformanceLeadership
	} from '@/common/api/renwu.js';
	import {
		getCurrentDate,
		getCurrentDateCN
	} from '@/utils/date.js';
	import {
		status_columns,
		type_columns
	} from '@/common/dataList.js'
	export default {
		props: ['performance', 'type', 'updateId'],
		data() {
			return {
				currentDateCN: '', // 中文格式日期
				form: {
					title: '',
					name: '',
					status: '',
					type: '',
					unit: '',
					lastCompletion:null,
				},
				fileList1: [],
				showSex: false,
				status_columns: status_columns,
				showtype: false,
				type_columns: type_columns,
				yj_status: '',
				yj_type: '',
				leader:[],
				reportingTime:''

			};
		},
		watch: {
			performance: {
				immediate: true,
				handler(newVal, oldVal) {
					this.form.title = newVal.title
					this.form.unit = newVal.unit
					this.reportingTime = newVal.reportingTime
				}
			},
			// 监听 updateId 变化
			updateId: {
				immediate: true, // 初始化时立即执行（处理初始传入的 updateId）
				async handler(newVal, oldVal) {
					console.log(newVal, oldVal, '-------updateId')
					// 1. 过滤无效值（null/undefined/空字符串）
					if (!newVal || newVal === '') {
						// this.data = null;
						this.getLeader()
						this.errorMsg = '';
						return; // 无有效值时不执行后续操作
					}

					// 2. 避免重复请求（若新值与旧值相同，且已有数据，则不重复请求）
					if (newVal === oldVal && this.data) {
						return;
					}
					
					try {
						// 3. 执行异步操作（接口请求）
						this.loading = true;
						this.errorMsg = '';

						// 查汇报详情
						const result = await this.getData(newVal);
						const leader = await this.getLeader(result.data.leadershipId)

						// 4. 处理接口返回数据
						// this.data = result;
						this.$nextTick(() => {
							this.form = {
								title: result.data.textPerformanceName,
								status: result.data.finishState,
								type: result.data.followThrough,
								name: Number(result.data.performanceContent),
								unit: result.data.unit,
								lastCompletion:Number(result.data.performanceContent),
							}
							this.yj_status = result.data.textFinishState
							this.yj_type = result.data.textFollowThrough
							// this.fileList1 = result.data.evidence
							 this.handleImgStr(result.data.evidence);
						})
						if(!this.reportingTime){
							this.reportingTime = this.$formatTime(result.data.createTime, 'YYYY-MM-DD')
						}
						console.log('接口请求成功，数据：', result);

					} catch (err) {
						// 5. 捕获错误并处理
						this.errorMsg = '数据加载失败，请稍后重试';
						console.error('接口请求失败：', err);
					} finally {
						// 6. 无论成功失败，结束加载状态
						this.loading = false;
					}
				}
			}
		},
		created() {
			// console.log(this.type, '======type======')
			// this.currentDateCN = getCurrentDateCN();
		},
		methods: {
			// 处理后端返回的图片字符串，转换为 fileList 格式
			handleImgStr(imgStr) {
				if (!imgStr) {
					this.fileList = [];
					return;
				}

				// 1. 按逗号分割为数组
				const imgArr = imgStr.split(',');

				// 2. 拼接域名并格式化为 fileList 结构
				this.fileList1 = imgArr.map((imgPath, index) => {
					// 提取文件名（从路径中截取，用于显示）
					const fileName = imgPath.split('/').pop();

					return {
						url: imgPath, // 拼接域名得到完整URL（关键）
						name: fileName, // 显示的文件名
						type: 'image', // 类型为图片
						uid: `img-${index}-${Date.now()}` // 生成唯一标识（避免删除时冲突）
					};
				});
			},
			confirm(e) {
				console.log('confirm', e)
				this.form.status = e.value[0].id
				this.yj_status = e.value[0].label
				this.showSex = false
			},
			confirm2(e) {
				console.log(e)
				this.form.type = e.value[0].id
				this.yj_type = e.value[0].label
				this.showtype = false

			},
			/**
			 * 处理输入事件，过滤非数字字符
			 * @param {String} val 输入的原始值
			 */
			handleInput(val) {
				console.log(val)
				// 1. 过滤非数字和非小数点的字符
				let filtered = val.replace(/[^\d.]/g, '');

				// 2. 限制只能有一个小数点
				filtered = filtered.replace(/^\./g, ''); // 禁止以小数点开头
				filtered = filtered.replace(/\.{2,}/g, '.'); // 禁止连续多个小数点

				// 3. 限制小数点后最多2位（如需更多位数，修改{1,2}为{1,n}）
				filtered = filtered.replace(/(\.\d{6})\d*/g, '$1');
				console.log(filtered)
				// 4. 同步到绑定值
				this.$nextTick(() => {
					this.form.name = filtered;
				});
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: "uploading",
						message: "上传中",
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: "success",
							message: "",
							url: result,
						})
					);
					fileListLen++;
					console.log(this.fileList1)
				}
			},

			async uploadFilePromise(url) {
				console.log('上传中')
				try {
					uni.showLoading({
						title: '上传中...'
					});
					const res = await http.upload('/wx/performance/addEvidence', url);
					console.log('图片上传结果：', res);
					return res; // 返回图片URL
				} catch (err) {
					console.error('上传失败：', err);
				}
			},
			async submit() {
				if (!this.form.name) {
					uni.showToast({
						title: '请填写汇报内容',
						icon: 'none'
					})
					return false;
				}
				if (!this.yj_status) {
					uni.showToast({
						title: '请选择完成状态',
						icon: 'none'
					})
					return false;
				}
				if (!this.yj_type) {
					uni.showToast({
						title: '请选择任务跟进方式',
						icon: 'none'
					})
					return false;
				}
				if (this.fileList1.length <= 0) {
					uni.showToast({
						title: '请上传凭证',
						icon: 'none'
					})
					return false;
				}
				let img = this.fileList1.map(item => item.url)
				let param = {
					sourceType: 1, // 0 开门红业务上报 1 我的任务业绩上报
					performanceName: this.performance.b_id, // 个人储蓄存款
					performanceContent: this.form.name,
					evidence: img.join(),
					finishState: this.form.status,
					followThrough: this.form.type,
					unit: this.form.unit,
					reportingTime:this.reportingTime
					

				}
				if(this.updateId){
					param.id = Number(this.updateId)
					param.lastCompletion = this.form.lastCompletion
				}
				console.log(param, '-----------this.performancename')
				try {
					await addPerformance(param).then(res => {
						console.log(res, '------------')
						uni.showToast({
							title: '提交成功'
						})
						setTimeout(() => {
							uni.redirectTo({
								url:'/homeNav/rwgl/ywsb?id=1'
							})
						}, 1500)
					})
				} catch (error) {
					// 捕获错误（来自拦截器或接口返回的错误）
					console.error('请求出错：', error);
					uni.showToast({
						title: error.msg,
						icon: 'none'
					})
				}
			},
			getData(id) {
				return selectPerformanceDetail({
					id: id
				})
			},
			
			// 查领导
			getLeader(leader){
				console.log(leader,'-------------leader')
				let params = {
					performanceName:this.performance.b_id,
					sourceType: 1, // 0 开门红业务上报 1 我的任务业绩上报
				}
				if(leader){
					params.leadershipId = leader
				}
				selectPerformanceLeadership(params).then(res=>{
					console.log(res,'-------------')
					this.leader = res.data
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.hbr-box {
		gap: 16rpx;
		flex-flow: wrap;
	}

	.hbr-item {
		border: 1rpx solid #2585f5;
		background-color: rgb(226, 238, 245);
		border-radius: 8rpx;
		padding: 4rpx 8rpx;
		box-sizing: border-box;
	}

	.title-box {
		font-size: 34rpx;
		font-weight: 500;
	}

	.btn-submit {
		width: 60%;
		margin: 100rpx 20% 40rpx;
		background-color: #2585f5;
		color: #fff;
		border-radius: 12rpx;
	}

	.btn-box {
		// width: 100%;
		// position: fixed;
		// bottom: 10%;
		// left: 0;
	}

	.btn-submit-2 {
		width: 40%;
		margin: 0 30%;
		// background-color: #2585f5;
		// color: #fff;
		border-radius: 12rpx;
	}

	.buttomboxs {
		width: 100%;
		background-color: white;
		display: flex;
		align-items: center;
		justify-content: space-between;
		position: fixed;
		z-index: 100;
		bottom: 0;
		border-top: 1px solid #fff7f6;
		padding: 20rpx 0;
		padding-bottom: constant(safe-area-inset-bottom);
		/* iOS 11.2+ 支持 env()，优先级更高 */
		padding-bottom: env(safe-area-inset-bottom);

		.butnavbox {
			width: 33.3%;

			.navimgs {
				width: 40rpx;
				height: 40rpx;
				margin: 0 auto;
				display: block;
				background-color: #ff5733;
				padding: 10rpx;
				border-radius: 15rpx;
			}

			.navtxt {
				text-align: center;
				font-size: 26rpx;
				margin-top: 10rpx;
				padding-bottom: 15rpx;
			}
		}
	}
</style>
<style>
	page {
		background-color: #fff;
	}
</style>